package com.zhixi.pattern.notimportant.interpreterpattern.operation;

import java.util.Map;
import java.util.Stack;

/**
 * @作者 ShuHaoNan
 * @邮箱 shuhaonan1@gmail.com
 * @时间 2020/11/20 14:23
 */
public class Calculator {

    private Expression expression;

    public Calculator(String expStr) {
        {
            Stack<Expression> stack = new Stack<>();
            char[] charArray = expStr.toCharArray();
            Expression left = null;
            Expression right = null;
            for (int i = 0; i < charArray.length; i++) {
                switch (charArray[i]) {
                    case '+':
                        left = stack.pop();
                        right = new VarExpression(String.valueOf(charArray[++i]));
                        stack.push(new AddExpression(left, right));
                        break;
                    case '-':
                        left = stack.pop();
                        right = new VarExpression(String.valueOf(charArray[++i]));
                        stack.push(new SubExpression(left, right));
                        break;
                    default:
                        stack.push(new VarExpression(String.valueOf(charArray[i])));
                }
            }
            this.expression = stack.pop();
        }
    }

    public int run(Map<String, Integer> var) {
        return this.expression.interpreter(var);
    }
}
